/**  
 * @Project: jeecg
 * @Title: ProcessEndListener.java
 * @Package com.oa.manager.workFlow.listener.execution
 * @date 2013-8-16 下午2:04:12
 * @Copyright: 2013 
 */
package org.jeecg.modules.extbpm.listener.execution;

import java.util.List;

import org.activiti.engine.HistoryService;
import org.activiti.engine.delegate.DelegateExecution;
import org.activiti.engine.delegate.ExecutionListener;
import org.activiti.engine.history.HistoricVariableInstance;
import org.activiti.engine.impl.persistence.entity.HistoricVariableInstanceEntity;
/*import org.jeecgframework.core.util.ApplicationContextUtil;
import org.jeecgframework.web.system.service.SystemService;
import org.jeecgframework.workflow.common.WorkFlowGlobals;
import org.jeecgframework.workflow.pojo.base.TPMutilFlowBizEntity;
import org.jeecgframework.workflow.service.impl.TaskJeecgService;*/
import org.jeecg.common.util.SpringContextUtils;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.extbpm.process.common.WorkFlowGlobals;
import org.jeecg.modules.extbpm.process.entity.ExtActFlowData;
import org.jeecg.modules.extbpm.process.mapper.ExtActDesignFlowDataMapper;
import org.jeecg.modules.extbpm.process.mapper.ExtActFlowDataMapper;
import org.jeecg.modules.extbpm.process.mapper.ExtActProcessMapper;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;

import lombok.extern.slf4j.Slf4j;
import org.jeecg.modules.extbpm.process.pojo.DesignFormDataDTO;
import org.springframework.beans.factory.annotation.Autowired;


/**
 * 	类名：ProcessEndListener
 * 	功能：流程实例结束监听器
 * @author zhoujf
 *
 */
@Slf4j
public class ProcessEndListener implements ExecutionListener{
	private static final long serialVersionUID = 1L;

	@Override
	public void notify(DelegateExecution execution) throws Exception {
//		
////		String applyUserId=(String)execution.getVariable("applyUserId");//获取流程发起人id
////		log.info("==流程结束=="+applyUserId);
//		
		log.info("流程结束监听开始");
		//修改流程状态
		doUpdateStatus(execution);
		
		//清空流程实例所有历史流程变量,任务变量
		HistoryService historyService= SpringContextUtils.getBean(HistoryService.class);
		
		List<HistoricVariableInstance> hvis=historyService.createHistoricVariableInstanceQuery().processInstanceId(execution.getProcessInstanceId()).list();
		
		for(HistoricVariableInstance h:hvis){
			//log.info(h.getVariableName());
			//流程对应的表单业务标题，不清空
			if(WorkFlowGlobals.BPM_DATA_ID.equals(h.getVariableName())){
				continue;
			}
			if(WorkFlowGlobals.BPM_FORM_KEY.equals(h.getVariableName())){
				continue;
			}
			if(WorkFlowGlobals.BPM_BIZ_TITLE.equals(h.getVariableName())){
				continue;
			}
			//流程办理风格，不清空
			if(WorkFlowGlobals.BPM_PROC_DEAL_STYLE.equals(h.getVariableName())){
				continue;
			}
			//流程对应的表单页面，不清空
			if(!WorkFlowGlobals.BPM_FORM_CONTENT_URL.equals(h.getVariableName()) && !WorkFlowGlobals.BPM_FORM_CONTENT_URL_MOBILE.equals(h.getVariableName())){
				((HistoricVariableInstanceEntity)h).delete();
			}
		}
		log.info("流程结束监听结束");
	}
	
	
	private void doUpdateStatus(DelegateExecution execution){
		String businessKey =  execution.getProcessBusinessKey();
		if(oConvertUtils.isEmpty(businessKey)) {
			return;
		}
		ExtActProcessMapper extActProcessMapper= SpringContextUtils.getBean(ExtActProcessMapper.class);
		ExtActFlowDataMapper extActFlowDataMapper= SpringContextUtils.getBean(ExtActFlowDataMapper.class);
        ExtActDesignFlowDataMapper extActDesignFlowDataMapper = SpringContextUtils.getBean(ExtActDesignFlowDataMapper.class);
		String bpmStatus=(String)execution.getVariable(WorkFlowGlobals.BPM_STATUS);//获取流程状态
//		String bpm_form_key = (String)execution.getVariable(WorkFlowGlobals.BPM_FORM_KEY);//获取流程对应的表单
//		String id = (String)execution.getVariable(WorkFlowGlobals.BPM_DATA_ID);//获取表单数据id
//		String formType = (String)execution.getVariable(WorkFlowGlobals.BPM_FORM_TYPE);//获取表单类型
		if(WorkFlowGlobals.PROCESS_CALLBACKPROCESS_STATUS.equals(bpmStatus)){
			//流程追回逻辑
			LambdaQueryWrapper<ExtActFlowData> queryWrapper = new LambdaQueryWrapper<ExtActFlowData>();
			queryWrapper.eq(ExtActFlowData::getFormDataId, businessKey);
			queryWrapper.eq(ExtActFlowData::getProcessInstId, execution.getProcessInstanceId());
			ExtActFlowData extActFlowData = extActFlowDataMapper.selectOne(queryWrapper);
			//更新表单状态
			if(extActFlowData!=null) {
				String tableName = extActFlowData.getFormTableName().toUpperCase();
				String col = extActFlowData.getBpmStatusField().toUpperCase();
				if(oConvertUtils.isEmpty(col)) {
					col = "BPM_STATUS";
				}
				extActProcessMapper.updateBpmStatusById(tableName, businessKey, col, WorkFlowGlobals.BPM_BUS_STATUS_1);
				extActFlowDataMapper.deleteById(extActFlowData.getId());
			}
			
		}else if(WorkFlowGlobals.PROCESS_INVALIDPROCESS_STATUS.equals(bpmStatus)){
			LambdaQueryWrapper<ExtActFlowData> queryWrapper = new LambdaQueryWrapper<ExtActFlowData>();
			queryWrapper.eq(ExtActFlowData::getFormDataId, businessKey);
			queryWrapper.eq(ExtActFlowData::getProcessInstId, execution.getProcessInstanceId());
			ExtActFlowData extActFlowData = extActFlowDataMapper.selectOne(queryWrapper);
			//更新表单状态
			if(extActFlowData!=null) {
				String tableName = extActFlowData.getFormTableName().toUpperCase();
				log.debug("-------tableName--------"+ tableName);
				String col = extActFlowData.getBpmStatusField().toUpperCase();
				if(oConvertUtils.isEmpty(col)) {
					col = "BPM_STATUS";
				}
				extActProcessMapper.updateBpmStatusById(tableName, businessKey, col, WorkFlowGlobals.BPM_BUS_STATUS_4);
				extActFlowData.setBpmStatus(WorkFlowGlobals.BPM_BUS_STATUS_4);
				extActFlowDataMapper.updateById(extActFlowData);
			}
		}else {
			LambdaQueryWrapper<ExtActFlowData> queryWrapper = new LambdaQueryWrapper<ExtActFlowData>();
			queryWrapper.eq(ExtActFlowData::getFormDataId, businessKey);
			queryWrapper.eq(ExtActFlowData::getProcessInstId, execution.getProcessInstanceId());
			ExtActFlowData extActFlowData = extActFlowDataMapper.selectOne(queryWrapper);
			//更新表单状态
			if(extActFlowData!=null) {
				String tableName = extActFlowData.getFormTableName().toUpperCase();
				String col = extActFlowData.getBpmStatusField().toUpperCase();
				if(oConvertUtils.isEmpty(col)) {
					col = "BPM_STATUS";
				}
				extActProcessMapper.updateBpmStatusById(tableName, businessKey, col, WorkFlowGlobals.BPM_BUS_STATUS_3);
				extActFlowData.setBpmStatus(WorkFlowGlobals.BPM_BUS_STATUS_3);
				extActFlowDataMapper.updateById(extActFlowData);

                //update-begin--Author:scott  Date:20191121 for：表单设计器表单 流程发起后，未回写物理表的流程状态
                //如果是表单设计器的表单，还需要回写关联物理表的流程状态
                String desFormCode = oConvertUtils.getString(execution.getVariable(WorkFlowGlobals.BPM_DES_FORM_CODE));
                String bpmDesDataId = oConvertUtils.getString(execution.getVariable(WorkFlowGlobals.BPM_DES_DATA_ID));
                String dbTableName = extActDesignFlowDataMapper.getDesignFormRelationTableName(desFormCode);
                DesignFormDataDTO designFormDataDto = extActDesignFlowDataMapper.getDesignFormDataById(bpmDesDataId);
				log.debug("----  流程结束监听，修改表单设计器的数据  ---");
				log.debug("--- dbTableName： " + dbTableName);
				log.debug("--- bpmDesDataId： " + bpmDesDataId);
				log.debug("--- col： "+ col);
                //通过表单设计编码，找对关联的物理表
                if(oConvertUtils.isNotEmpty(dbTableName) && designFormDataDto!=null && oConvertUtils.isNotEmpty(designFormDataDto.getOnlineFormDataId())){
				log.debug("--- designFormDataDto.getOnlineFormDataId()： "+ designFormDataDto.getOnlineFormDataId());
                    extActProcessMapper.updateBpmStatusById(dbTableName, designFormDataDto.getOnlineFormDataId(), col, WorkFlowGlobals.BPM_BUS_STATUS_3);
                }
                //update-end--Author:scott  Date:20191121 for：表单设计器表单 流程发起后，未回写物理表的流程状态
			}
		}
	}

}
